package com.english.controller.admin;

import com.english.entity.Lesson;
import com.english.entity.LessonLog;
import com.english.entity.StudentRecharge;
import com.english.mapper.UserMapper;
import com.english.service.LessonService;
import com.english.utils.R;
import com.english.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.math.BigDecimal;

@RestController
@RequestMapping("/api/lesson/admin")
@CrossOrigin(origins = "*", allowCredentials = "false", maxAge = 3600)
public class AdminLessonController extends AdminBaseController {

    @Autowired
    private LessonService lessonService;

    @Autowired
    private UserMapper userMapper;

    /**
     * 管理员获取学生列表
     *
     * @param token 管理员token
     * @param keyword 搜索关键词（可选）
     * @param filter 过滤条件（可选）
     * @return 学生列表
     */
    @GetMapping("/students")
    public R<List<StudentListVO>> getStudentList(
            @RequestHeader("Authorization") String token,
            @RequestParam(value = "keyword", required = false) String keyword,
            @RequestParam(value = "filter", defaultValue = "all") String filter) {
        try {
            Long adminId = getAdminId(token);
            List<StudentListVO> students = lessonService.getStudentList(keyword, filter);
            return R.success("获取学生列表成功", students);
        } catch (RuntimeException e) {
            return R.error(e.getMessage());
        }
    }

    /**
     * 管理员获取课时管理统计数据
     *
     * @param token 管理员token
     * @return 统计数据
     */
    @GetMapping("/stats")
    public R<LessonStatsVO> getAdminStats(@RequestHeader("Authorization") String token) {
        try {
            Long adminId = getAdminId(token);
            LessonStatsVO stats = lessonService.getAdminStats();
            return R.success("获取统计数据成功", stats);
        } catch (RuntimeException e) {
            return R.error(e.getMessage());
        }
    }



    /**
     * 批量调整课时
     *
     * @param token 管理员token
     * @param operationVO 批量操作信息
     * @return 操作结果
     */
    @PostMapping("/batch-adjust")
    public R<String> batchAdjust(
            @RequestHeader("Authorization") String token,
            @RequestBody BatchOperationVO operationVO) {
        try {
            Long adminId = getAdminId(token);
            boolean success = lessonService.batchAdjust(operationVO, adminId);
            return success ? R.success("批量调整成功", null) : R.error("批量调整失败");
        } catch (RuntimeException e) {
            return R.error(e.getMessage());
        }
    }

    /**
     * 查询学生课时实时数据
     *
     * @param studentId 学生ID
     * @return 课时信息
     */
    @GetMapping("/info")
    public R<Lesson> getLessonInfo(@RequestParam("studentId") Long studentId) {
        Lesson lesson = lessonService.getLessonByStudentId(studentId);
        if (lesson == null) {
            return R.error("未找到该学生课时信息");
        }
        return R.success("查询成功", lesson);
    }

    /**
     * 查询学生课时变动记录
     *
     * @param studentId 学生ID
     * @return 课时变动记录列表
     */
    @GetMapping("/logs")
    public R<List<LessonLog>> getLessonLogs(@RequestParam("studentId") Long studentId) {
        List<LessonLog> logs = lessonService.getLessonLogsByStudentId(studentId);
        return R.success("查询成功", logs);
    }

    /**
     * 管理员调整单个学生课时
     *
     * @param token 管理员token
     * @param adjustVO 课时调整信息
     * @return 操作结果
     */
    @PostMapping("/adjust")
    public R<String> adjustLesson(
            @RequestHeader("Authorization") String token,
            @RequestBody LessonAdjustVO adjustVO) {
        try {
            Long adminId = getAdminId(token);
            boolean ok = lessonService.adjustLesson(adjustVO, adminId);
            return ok ? R.success("课时调整成功", null) : R.error("课时调整失败");
        } catch (RuntimeException e) {
            return R.error(e.getMessage());
        }
    }

    // 管理员查询学生充值待办记录
    @GetMapping("/getStudentRechargeList")
    public R<List<StudentRecharge>> getStudentRechargeList() {
        List<StudentRecharge> list = lessonService.getStudentRechargeList();
        return R.success(list);
    }

    // 管理员处理代办
    @PutMapping("/handleStudentRecharge")
    public R<String> handleStudentRecharge(
            @RequestHeader("Authorization") String token,
            @RequestParam Long userId,
            @RequestParam Integer hoursAdded,
            @RequestParam(required = false) Integer classId,
            @RequestParam(required = false) String processNotes) {
        try {
            Long adminId = getAdminId(token);
            lessonService.handleStudentRecharge(userId, adminId, hoursAdded, classId, processNotes);
            return R.success("处理成功");
        } catch (RuntimeException e) {
            return R.error(e.getMessage());
        }
    }

    // 管理员处理充值 - 支持多班级分配
    @PutMapping("/handleStudentRechargeMultiClass")
    public R<String> handleStudentRechargeMultiClass(
            @RequestHeader("Authorization") String token,
            @RequestBody Map<String, Object> requestData) {
        try {
            Long adminId = getAdminId(token);
            Long userId = Long.valueOf(requestData.get("userId").toString());
            String processNotes = (String) requestData.get("processNotes");
            
            // 解析班级课时分配
            @SuppressWarnings("unchecked")
            Map<String, Integer> classHoursStrMap = (Map<String, Integer>) requestData.get("classHours");
            Map<Long, Integer> classHoursMap = new HashMap<>();
            for (Map.Entry<String, Integer> entry : classHoursStrMap.entrySet()) {
                classHoursMap.put(Long.valueOf(entry.getKey()), entry.getValue());
            }
            
            lessonService.handleStudentRechargeMultiClass(userId, adminId, classHoursMap, processNotes);
            return R.success("多班级充值处理成功");
        } catch (RuntimeException e) {
            return R.error(e.getMessage());
        }
    }

    // 获取班级价格信息
    @GetMapping("/getClassPrices")
    public R<Map<Long, BigDecimal>> getClassPrices() {
        try {
            Map<Long, BigDecimal> classPrices = lessonService.getClassPrices();
            return R.success(classPrices);
        } catch (RuntimeException e) {
            return R.error(e.getMessage());
        }
    }

    // 获取充值处理日志
    @GetMapping("/getRechargeProcessLogs")
    public R<List<RechargeProcessLogVO>> getRechargeProcessLogs() {
        List<RechargeProcessLogVO> logs = lessonService.getRechargeProcessLogs();
        return R.success(logs);
    }

    // 根据用户ID获取用户信息
    @GetMapping("/getUserById")
    public R<com.english.entity.User> getUserById(@RequestParam Long userId) {
        try {
            com.english.entity.User user = userMapper.selectById(userId);
            if (user != null) {
                return R.success("获取成功", user);
            } else {
                return R.error("用户不存在");
            }
        } catch (Exception e) {
            return R.error("获取用户信息失败: " + e.getMessage());
        }
    }

    /**
     * 批量充值课时
     *
     * @param token 管理员token
     * @param batchRechargeVO 批量充值信息
     * @return 操作结果
     */
    @PostMapping("/batch-recharge")
    public R<String> batchRecharge(
            @RequestHeader("Authorization") String token,
            @RequestBody BatchRechargeVO batchRechargeVO) {
        try {
            // 获取管理员ID（如果需要记录）
            Long adminId = getAdminId(token);
            boolean success = lessonService.batchRecharge(batchRechargeVO, adminId);
            return success ? R.success("批量充值成功") : R.error("批量充值失败");
        } catch (RuntimeException e) {
            return R.error(e.getMessage());
        }
    }
}

